package de.bk.timecalc.gui;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;

/**
 * Main class for the time calc gui application
 * 
 * @author Bastian Krol
 */
public class TimeCalcGui
{
  private Display display;

  private GameWindowBehaviour behaviour;
  private MenuBar menuBar;

  private void start()
  {
    this.init();
    this.eventLoop();
    this.display.dispose();
  }

  private void init()
  {
    SettingsModel settingsModel = new SettingsModel();

    this.display = new Display();
    this.behaviour = new GameWindowBehaviour(settingsModel);
    this.behaviour.init(this.display);
    this.menuBar = new MenuBar(this.behaviour);
    this.menuBar.initMenu(this.behaviour.getShell());

    this.behaviour.openShell();
    this.behaviour.nextChallenge();

    SettingsWindow settingsWindow = new SettingsWindow(this.behaviour);
    settingsWindow.init(this.behaviour.getShell());
    this.behaviour.setSettingsWindow(settingsWindow);

    HelpWindow helpWindow = new HelpWindow();
    helpWindow.init(this.behaviour.getShell());
    this.behaviour.setHelpWindow(helpWindow);
  }

  private void eventLoop()
  {
    try
    {
      while (!this.behaviour.getShell().isDisposed())
      {
        if (!this.display.readAndDispatch())
        {
          this.display.sleep();
        }
      }
      if (!this.display.isDisposed())
      {
        this.display.dispose();
      }
    }
    catch (Throwable t)
    {
      System.err.println(t.getMessage());
      t.printStackTrace();
      StringBuffer message = new StringBuffer();
      message
          .append("An unexpected error occured. The application will exit.\n");
      message.append(t.getClass().getName());
      message.append("\n");
      if (t.getMessage() != null)
      {
        message.append(t.getMessage());
        message.append("\n");
      }
      message.append("\nStack Trace:\n");
      for (StackTraceElement stackTraceElement : t.getStackTrace())
      {
        message.append(stackTraceElement.toString());
        message.append("\n");
      }
      GuiToolbox.openOkPopup(this.behaviour.getShell(), "Unknown Error",
          message.toString(), SWT.ICON_ERROR);
    }
    finally
    {
      this.behaviour.dispose();
    }
  }

  /**
   * Main method.
   * 
   * @param arguments
   *          all command line arguments are ignored
   */
  public static void main(String[] arguments)
  {
    TimeCalcGui gui = new TimeCalcGui();
    gui.start();
  }
}
